<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-select
          v-model="queryParams.projectId"
          placeholder="请选择项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="(item, index) in projectNameList"
            :key="index"
            :label="item.projectName"
            :value="item.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工程名称" prop="engineeringName">
        <el-input
          v-model="queryParams.engineeringName"
          placeholder="请输入工程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工程编号" prop="engineeringCode">
        <el-input
          v-model="queryParams.engineeringCode"
          placeholder="请输入工程编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建设地点" prop="constructionSite">
        <el-input
          v-model="queryParams.constructionSite"
          placeholder="请输入建设地点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用年限" prop="serviceLife">
        <el-input
          v-model="queryParams.serviceLife"
          placeholder="请输入使用年限"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工程里程" prop="mileage">
        <el-input
          v-model="queryParams.mileage"
          placeholder="请输入工程里程"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建设单位" prop="constructionUnit">
        <el-input
          v-model="queryParams.constructionUnit"
          placeholder="请输入建设单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设计单位" prop="designUnit">
        <el-input
          v-model="queryParams.designUnit"
          placeholder="请输入设计单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="施工单位" prop="constructionCorp">
        <el-input
          v-model="queryParams.constructionCorp"
          placeholder="请输入施工单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择施工开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择施工结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="运维单位" prop="operationCorp">
        <el-input
          v-model="queryParams.operationCorp"
          placeholder="请输入运维单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编制人员" prop="carbonCompiler">
        <el-input
          v-model="queryParams.carbonCompiler"
          placeholder="请输入碳排放编制人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:engineering:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:engineering:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:engineering:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="upload.open = true"
          v-hasPermi="['business:engineering:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:engineering:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-s-marketing"
          size="mini"
          :disabled="two"
          @click="compareData"
        >对比</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="engineeringList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="projectName" v-if="columns[15].visible" />
      <el-table-column label="工程名称" align="center" prop="engineeringName" v-if="columns[1].visible" />
      <el-table-column label="工程编号" align="center" prop="engineeringCode" v-if="columns[2].visible" />
      <el-table-column label="建设地点" align="center" prop="constructionSite" v-if="columns[3].visible" />
      <el-table-column label="使用年限" align="center" prop="serviceLife" v-if="columns[4].visible" />
      <el-table-column label="工程里程" align="center" prop="mileage" v-if="columns[5].visible" />
      <el-table-column label="建设单位" align="center" prop="constructionUnit" v-if="columns[6].visible" />
      <el-table-column label="设计单位" align="center" prop="designUnit" v-if="columns[7].visible" />
      <el-table-column label="施工单位" align="center" prop="constructionCorp" v-if="columns[8].visible" />
      <el-table-column label="施工开始时间" align="center" prop="startTime" v-if="columns[9].visible" />
      <el-table-column label="施工结束时间" align="center" prop="endTime" v-if="columns[10].visible" />
      <el-table-column label="运维单位" align="center" prop="operationCorp" v-if="columns[11].visible" />
      <el-table-column label="碳排放编制人员" align="center" prop="carbonCompiler" v-if="columns[12].visible" />
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[14].visible" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="handleCarbon(scope.row)"
          >碳排放计算</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-pie-chart"
            @click="handleResult(scope.row)"
          >计算结果</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:engineering:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:engineering:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工程信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="projectId">
          <el-select
            v-model="form.projectId"
            placeholder="请选择项目名称"
            clearable
          >
            <el-option
              v-for="(item, index) in projectNameList"
              :key="index"
              :label="item.projectName"
              :value="item.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工程名称" prop="engineeringName">
          <el-input v-model="form.engineeringName" placeholder="请输入工程名称" />
        </el-form-item>
        <el-form-item label="工程编号" prop="engineeringCode">
          <el-input v-model="form.engineeringCode" placeholder="请输入工程编号" />
        </el-form-item>
        <el-form-item label="建设地点" prop="constructionSite">
          <el-input v-model="form.constructionSite" placeholder="请输入建设地点" />
        </el-form-item>
        <el-form-item label="使用年限" prop="serviceLife">
          <el-input v-model="form.serviceLife" placeholder="请输入使用年限" />
        </el-form-item>
        <el-form-item label="工程里程" prop="mileage">
          <el-input v-model="form.mileage" placeholder="请输入工程里程" />
        </el-form-item>
        <el-form-item label="建设单位" prop="constructionUnit">
          <el-input v-model="form.constructionUnit" placeholder="请输入建设单位" />
        </el-form-item>
        <el-form-item label="设计单位" prop="designUnit">
          <el-input v-model="form.designUnit" placeholder="请输入设计单位" />
        </el-form-item>
        <el-form-item label="施工单位" prop="constructionCorp">
          <el-input v-model="form.constructionCorp" placeholder="请输入施工单位" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择施工开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择施工结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="运维单位" prop="operationCorp">
          <el-input v-model="form.operationCorp" placeholder="请输入运维单位" />
        </el-form-item>
        <el-form-item label="编制人员" prop="carbonCompiler">
          <el-input v-model="form.carbonCompiler" placeholder="请输入碳排放编制人员" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入工程信息对话框 -->
    <excel-upload
      :title="upload.title"
      :uploadUrl="upload.url"
      :open="upload.open"
      @uploadClose="upload.open = false"
      @handleFileSuccess="getList">
    </excel-upload>

    <!-- 预览界面 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body class="scrollbar" @close="closeDialog">
      <el-tabs :value="preview.activeName" @tab-click="handleClick">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="value"
          :name="value"
          :key="value"
          :disabled="tabDisabled"
        >
          <project-basic-info
            :project-data="projectData"
            :usagePhase="preview.activeName"
            :engineering-names-data="engineeringName"
          />

          <!-- 设备 -->
          <equipment-emission
            :equipment-data="equipmentInfoList"
            :usagePhase="preview.activeName"
            @refreshEquipmentInfo="refreshEquipmentInfo"
            @openEquipmentDialog="openEquipmentDialog"
            v-show="preview.activeName !== '建材生产运输阶段'"
          />

          <!-- 材料运输产生的碳排放 -->
          <material-transport
            :transport-data="materialInfoList"
            :usagePhase="preview.activeName"
            @refreshTransportInfo="refreshTransportInfo"
            @openMaterialDialog="openMaterialDialog"
            v-show="preview.activeName === '建材生产运输阶段' || preview.activeName === '运营维护阶段' || preview.activeName === '拆除处置阶段'"
          />

          <!-- 人员 -->
          <personnel-emission
            :personnel-data="personnelData"
            :usagePhase="preview.activeName"
            :engineeringId="engineeringId"
            @updatePersonnelData="updatePersonnelData"
            v-show="preview.activeName !== '建材生产运输阶段'"
          />

          <!-- 临时(绿地)设施能源碳排放 -->
          <energy-emission
            :equipment-data="keywordList"
            :usagePhase="preview.activeName"
            @refreshEquipmentInfo="getKeywordList"
            @openEquipmentDialog="openEnergyDialog"
            :keyword="keyword"
            v-if="preview.activeName === '施工阶段' || preview.activeName === '运营维护阶段'"
          />

          <!-- 回收减碳排放 -->
          <carbon-emission
            :equipment-data="carbonList"
            :usagePhase="preview.activeName"
            @refreshEquipmentInfo="getCarbonList"
            @openEquipmentDialog="openEnergyDialog"
            :keyword="keyword"
            v-show="preview.activeName === '拆除处置阶段'"
          />

          <!-- 电力消耗车辆行驶碳排放 -->
          <car-emission
            :carData="carData"
            :mileage="mileage"
            :serviceLife="serviceLife"
            :usagePhase="preview.activeName"
            :engineeringId="engineeringId"
            :projectId="phaseParams.projectId"
            @updateCarData="updateCarData"
            v-if="preview.activeName === '运营维护阶段'"
          ></car-emission>

        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="closeDialog">计 算</el-button>
        <el-button type="primary" @click="nextTab">下一步</el-button>
        <el-button @click="preview.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备弹窗 -->
    <equipment-config
      ref="equipmentRef"
     :usagePhase="preview.activeName"
     :equipmentType="preview.equipmentType"
     :equipmentForm="preview.equipmentForm"
     :engineeringId="engineeringId"
     @refreshEquipmentInfo="refreshEquipmentInfo"
     @refreshKeywordInfo="getKeywordList"
     @refreshCarbonList="getCarbonList"
    />

    <!-- 材料运输弹窗 -->
    <transport-config
      ref="materialRef"
      :usagePhase="preview.activeName"
      :engineeringId="engineeringId"
      @refreshMaterialInfo="refreshTransportInfo" />
  </div>
</template>

<script>
import {
  listEngineering,
  getEngineering,
  addEngineering,
  updateEngineering,
  delEngineering,
  getPhase,
  savePhase,
  listAll
} from "@/api/business/engineering"
import { listEquipmentInfo, addEquipmentInfo, updateEquipmentInfo, delEquipmentInfo } from "@/api/business/equipmentInfo"
import { listPersionEmission, getPersionEmission, addPersionEmission, updatePersionEmission, delPersionEmission } from "@/api/business/persionEmission"
import { listProjectInfo } from "@/api/business/projectInfo"
import { listMasterialTransport } from "@/api/business/masterialTransport"
import { listOperationPhase } from "@/api/business/operationPhase"
import EquipmentConfig from "./EquipmentConfig.vue"
import ProjectBasicInfo from './ProjectBasicInfo.vue';
import TransportConfig from './TransportConfig.vue';
import EnergyEmission from './EnergyEmission.vue';
import EquipmentEmission from './EquipmentEmission.vue';
import CarbonEmission from './CarbonEmission.vue';
import PersonnelEmission from './PersonnelEmission.vue';
import CarEmission from './CarEmission.vue';
import MaterialTransport from "./MaterialTransport.vue";

export default {
  name: "Engineering",
  components: { EquipmentConfig, EnergyEmission, CarEmission, CarbonEmission, TransportConfig, ProjectBasicInfo, EquipmentEmission, PersonnelEmission, MaterialTransport },
  data() {
    return {
      tabDisabled: false,
      projectData: {
        projectName: '项目名称',
        projectSection: '项目标段',
        mileage: 1,
        totalEmission: 1
      },
      engineeringName: '工程名称',
      personnelData: {
        totalPersonnel: null,
        workDays: null,
        emissionFactor: null
      },
      carData: {
        avgElectricity: 0,
        designLife: 0,
        gridCarbonFactor: 0,

        initialDailyTraffic: 0,
        vehicleEmissionFactor: 0,
        trafficGrowthRate: 0,
      },

      mileage: 0,
      serviceLife: 0,

      // 工程名称
      projectNameList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 两个
      two: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工程信息表格数据
      engineeringList: [],
      // 设备信息
      equipmentInfoList: [],
      // 运输信息
      materialInfoList: [],
      // 临时(绿地)设备碳排放量
      keywordList: [],
      // 减碳排放量
      carbonList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入Excel参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "工程信息导入",
        // 上传的地址
        url: "/business/engineering/importData"
      },
      // 显隐列
      columns: [
        { key: 1, label: `工程ID`, visible: true },
        { key: 2, label: `工程名称`, visible: true },
        { key: 3, label: `工程编号`, visible: true },
        { key: 4, label: `建设地点`, visible: true },
        { key: 5, label: `使用年限`, visible: true },
        { key: 6, label: `工程里程`, visible: true },
        { key: 7, label: `建设单位`, visible: true },
        { key: 8, label: `设计单位`, visible: true },
        { key: 9, label: `施工单位`, visible: true },
        { key: 10, label: `施工开始时间`, visible: true },
        { key: 11, label: `施工结束时间`, visible: true },
        { key: 12, label: `运维单位`, visible: true },
        { key: 13, label: `碳排放编制人员`, visible: true },
        { key: 14, label: `碳排放因子`, visible: true },
        { key: 15, label: `备注`, visible: false },
        { key: 16, label: `项目名称`, visible: true },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        engineeringName: null,
        engineeringCode: null,
        constructionSite: null,
        serviceLife: null,
        mileage: null,
        constructionUnit: null,
        designUnit: null,
        constructionCorp: null,
        startTime: null,
        endTime: null,
        operationCorp: null,
        carbonCompiler: null,
        carbonFactor: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        engineeringName: [
          { required: true, message: "工程名称不能为空", trigger: "blur" }
        ],
        engineeringCode: [
          { required: true, message: "工程编号不能为空", trigger: "blur" }
        ],
      },
      engineeringId: null,
      keyword: "",
      preActiveName: null,
      // 预览参数
      preview: {
        open: false,
        title: "碳排放计算",
        data: ["勘察设计阶段", "建材生产运输阶段", "施工阶段", "运营维护阶段", "拆除处置阶段"],
        activeName: "勘察设计阶段",
        equipmentType: "设备",
        equipmentTypeData: ["设备", "材料"],
        equipmentForm: "设备列表",
        equipmentFormData: ["设备列表", "运输列表", "建材列表", "能源列表", "汇碳列表"],
        index: 0,
        preIndex: 0
      },
      // 碳排放参数
      phaseParams: {
        projectId: null,
        engineeringId: null,
        usagePhase: null,
        totalEmission: null
      }
    }
  },
  created() {
    const projectId = this.$route.params && this.$route.params.projectId
    if (projectId !== undefined && projectId != 0) {
      this.queryParams.projectId = projectId
      this.getList()
    } else {
      this.getList()
    }
    // 获取所有的项目
    this.getProject()
  },
  methods: {
    /** 获取项目 **/
    getProject() {
      let param = {"allData": true}
      listProjectInfo(param).then(response => {
        response.rows.forEach((item) => {
          this.projectNameList.push({
            projectId: item.projectId,
            projectName: item.projectName
          })
        })
      })
    },
    /** 查询工程信息列表 */
    getList() {
      this.loading = true
      listEngineering(this.queryParams).then(response => {
        this.engineeringList = response.rows
        this.total = Number(response.total)
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        engineeringId: null,
        engineeringName: null,
        engineeringCode: null,
        constructionSite: null,
        serviceLife: null,
        mileage: null,
        constructionUnit: null,
        designUnit: null,
        constructionCorp: null,
        startTime: null,
        endTime: null,
        operationCorp: null,
        carbonCompiler: null,
        carbonFactor: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.engineeringId)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.two = this.ids.length !== 2
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加工程信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const engineeringId = row.engineeringId || this.ids
      getEngineering(engineeringId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改工程信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.engineeringId != null) {
            updateEngineering(this.form.engineeringId, this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addEngineering(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const engineeringIds = row.engineeringId || this.ids
      this.$modal.confirm('是否确认删除工程信息编号为"' + engineeringIds + '"的数据项？').then(function() {
        return delEngineering(engineeringIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/engineering/export', {
        ...this.queryParams
      }, `engineering_export_${this.parseTime(new Date())}.xlsx`)
    },
    /** 获取设备信息列表 */
    getEquipmentInfo() {
      listEquipmentInfo({ allData: true, usagePhase:
        this.preview.activeName,
        equipmentForm: "设备列表",
        equipmentType: "设备",
        engineeringId: this.engineeringId }).then(response => {
        this.equipmentInfoList = response.rows
      })
    },
    /** 获取运输信息列表 */
    getMaterialInfoList() {
      listMasterialTransport({ allData: true, usagePhase: this.preview.activeName, engineeringId: this.engineeringId }).then(response => {
        this.materialInfoList = response.rows
      })
    },
    /** 获取汇碳信息列表 */
    getKeywordList() {
      let currentEquipmentForm = null
      if (this.preview.activeName === "施工阶段") {
        currentEquipmentForm = "能源列表"
      } else if (this.preview.activeName === "运营维护阶段") {
        currentEquipmentForm = "汇碳列表"
      }
      listEquipmentInfo({
        allData: true,
        usagePhase: this.preview.activeName,
        equipmentForm: currentEquipmentForm,
        equipmentType: "材料",
        engineeringId: this.engineeringId }).then(response => {
        this.keywordList = response.rows
      })
    },
    getCarbonList() {
      listEquipmentInfo({
        allData: true,
        usagePhase: this.preview.activeName,
        equipmentForm: "回收列表",
        equipmentType: "材料",
        engineeringId: this.engineeringId }).then(response => {
        this.carbonList = response.rows
      })
    },
    refreshTransportInfo() {
      this.getMaterialInfoList()
    },
    /** 碳排放计算 **/
    handleCarbon(row) {
      this.engineeringId = row.engineeringId
      this.projectData.projectName = row.engineeringName
      this.projectData.projectSection = row.constructionSite
      this.projectData.mileage = row.mileage
      this.engineeringName = row.engineeringName
      this.preview.open = true
      this.phaseParams.projectId = row.projectId
      this.phaseParams.engineeringId = this.engineeringId

      this.mileage = row.mileage ? row.mileage : 0
      this.serviceLife = row.serviceLife ? row.serviceLife : 0
      this.refreshData(false)
    },
    /** 计算结果 **/
    handleResult(row) {
      // 路由跳转
      const engineeringId = row.engineeringId || 0
      const projectId = row.projectId || 0
      this.$router.push({
        path: '/carbon/business-project/businessEngineeringResult/' + projectId + "/" + engineeringId ,
        query: {
          mileage: row.mileage || 1,
          serviceLife: row.serviceLife || 1,
        }
      })
    },
    // 刷新获取的数据
    async refreshData(save=true) {
      if (save) {
        // 保存计算结果
        await this.savePhaseResult(await this.calculate())
      }
      // 已经更换了标签页
      this.equipmentInfoList = []
      this.materialInfoList = []
      this.keywordList = []
      this.carbonList = []
      this.personnelData = {
        totalPersonnel: null,
        workDays: null,
        emissionFactor: null
      }
      this.carData = {
        avgElectricity: 0,
        designLife: 0,
        gridCarbonFactor: 0,

        initialDailyTraffic: 0,
        vehicleEmissionFactor: 0,
        trafficGrowthRate: 0,
      }
      // 获取碳排放信息
      this.getPhaseResult()
      if (this.preview.activeName !== '建材生产运输阶段') {
        // 获取设备数据
        this.refreshEquipmentInfo()
        // 获取人员信息
        this.getPersionEmission()
      }
      if (this.preview.activeName === '建材生产运输阶段' || this.preview.activeName === '运营维护阶段') {
        // 获取运输信息
        this.getMaterialInfoList()
        // 获取电力车辆运输碳排放量
        this.getCarDataList()
      }
      if (this.preview.activeName === '施工阶段' || this.preview.activeName === '运营维护阶段') {
        // 获取汇碳(绿地)列表
        this.getKeywordList()
      }
      if (this.preview.activeName === '拆除处置阶段') {
        // 获取回收减碳列表
        this.getCarbonList()
      }
    },
    // 获取碳排放信息
    getPhaseResult() {
      this.phaseParams.usagePhase = this.preview.data[this.preview.index]
      getPhase(this.phaseParams).then(response => {
        if (response.data && response.data.totalEmission !== null) {
          this.projectData.totalEmission = response.data.totalEmission
        }
      })
    },
    // 保存碳排放信息
    async savePhaseResult(totalEmission) {
      this.phaseParams.totalEmission = totalEmission
      this.phaseParams.usagePhase = this.preview.activeName
      await savePhase(this.phaseParams)
      this.tabDisabled = false
    },
    // 切换标签页触发事件
    async handleClick(tab, event) {
      this.tabDisabled = true
      await this.savePhaseResult(await this.calculate())
      this.preview.activeName = tab.name
      if (this.preview.activeName === "施工阶段") {
        this.keyword = "能源"
      } else if (this.preview.activeName === "运营维护阶段") {
        this.keyword = "绿地"
      }
      this.preview.preIndex = this.preview.index
      this.preview.index = this.preview.data.indexOf(tab.name)
      this.refreshData(false)
    },
    // 打开弹窗选择数据
    openEquipmentDialog() {
      this.keyword = "设备"
      this.$refs.equipmentRef.show(this.keyword)
    },
    // 开启汇碳和绿地
    openEnergyDialog() {
      if (this.preview.activeName === "施工阶段") {
        this.keyword = "能源"
      } else if (this.preview.activeName === "运营维护阶段") {
        this.keyword = "绿地"
      } else if (this.preview.activeName === "拆除处置阶段") {
        this.keyword = "回收"
      }
      this.$refs.equipmentRef.show(this.keyword)
    },
    // 打开弹窗选择数据
    openMaterialDialog() {
      this.$refs.materialRef.show()
    },
    /** 刷新设备配置信息 */
    refreshEquipmentInfo() {
      this.getEquipmentInfo()
    },
    // 获取人员信息
    getPersionEmission() {
      listPersionEmission({ usagePhase: this.preview.activeName, engineeringId: this.engineeringId }).then(response => {
        if (response.rows) {
          this.personnelData = response.rows[0]
        }
      })
    },
    // 获取电力车辆碳排放量
    getCarDataList() {
      listOperationPhase({ usagePhase: this.preview.activeName, engineeringId: this.engineeringId }).then(response => {
        if (response.rows) {
          if (!response.rows[0]) {
            return
          }
          this.carData.operationId = response.rows[0].operationId
          this.carData.avgElectricity = response.rows[0].avgElectricity
          this.carData.designLife = response.rows[0].designLife
          this.carData.gridCarbonFactor = response.rows[0].gridCarbonFactor
          this.carData.initialDailyTraffic = response.rows[0].initialDailyTraffic
          this.carData.vehicleEmissionFactor = response.rows[0].vehicleEmissionFactor
          this.carData.trafficGrowthRate = response.rows[0].trafficGrowthRate
        }
      })
    },
    // 下一个标签页
    async nextTab() {
      this.tabDisabled = true
      let number = this.preview.index + 1
      if (number < this.preview.data.length) {
        this.preview.activeName = this.preview.data[number]
        this.preview.preIndex = this.preview.index
        this.preview.index = number
        await this.refreshData()
        this.$modal.msgSuccess("下一步为：" + this.preview.activeName)
      } else {
        this.$modal.msgError("已经到最后一项")
      }
    },
    async calculate() {
      let result = 0
      // 计算设备碳排放量
      this.equipmentInfoList.forEach((item) => {
        result = result + item.carbonFactor * item.shiftCount
      })
      // 计算人员碳排放量
      if (this.personnelData && this.personnelData.totalPersonnel !== null) {
        result = result + this.personnelData.totalPersonnel * this.personnelData.emissionFactor * this.personnelData.workDays
      }
      // 计算运输碳排放量（废物运输碳排放量）
      this.materialInfoList.forEach((item) => {
        result = result + this.preview.activeName === '拆除处置阶段' ?
          (item.quantity * item.conversionFactor * item.transportDistance * item.transportFactor).toFixed(2) :
          (item.quantity * item.carbonFactor + item.quantity * item.transportDistance * item.conversionFactor * item.transportFactor).toFixed(2)
      })
      // 计算临时(绿地)
      this.keywordList.forEach((item) => {
        if (this.keyword === "能源") {
          result = result + item.carbonFactor * item.shiftCount
        } else {
          result = result - item.carbonFactor * item.shiftCount
        }
      })
      // 回收减碳列表
      this.carbonList.forEach((item) => {
        result = result - item.carbonFactor * item.shiftCount * item.remark
      })
      // 计算电力消耗和车辆行驶
      result = result + this.carData.avgElectricity * this.carData.designLife * this.carData.gridCarbonFactor
      // result = result + this.mileage * this.serviceLife * this.carData.initialDailyTraffic * this.carData.vehicleEmissionFactor * this.carData.trafficGrowthRate
      if (this.carData.trafficGrowthRate === 0) {
        result = result + this.serviceLife
          * 365 * this.mileage * this.carData.initialDailyTraffic * this.carData.vehicleEmissionFactor
      } else {
        result = result + (((1 + this.carData.trafficGrowthRate) ** this.serviceLife - 1) / this.carData.trafficGrowthRate)
          * 365 * this.mileage * this.carData.initialDailyTraffic * this.carData.vehicleEmissionFactor
      }

      if ((this.preview.activeName === "运营维护阶段" || this.preview.activeName === "拆除处置阶段") && result <= 0) {
        // 认为没有拆除维修数据，按照"工程建造阶段"10%计入
        let res = await listAll({ projectId: this.phaseParams.projectId, engineeringId: this.phaseParams.engineeringId})
        result = ((res.data[1].totalEmission ? res.data[1].totalEmission : 0 + res.data[2].totalEmission ? res.data[2].totalEmission : 0) * 0.1).toFixed(2)
      }
      result = parseFloat(result)
      if (result <= 0) {
        this.projectData.totalEmission = 0
      } else {
        this.projectData.totalEmission = result
      }
      return result
    },
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    // 关闭提示框
    async closeDialog() {
      await this.savePhaseResult(await this.calculate())
      this.sleep(1000).then(() => {
        this.$modal.msgSuccess("已保存数据")
      })
    },
    // 跳转到对比界面
    compareData() {
      const compareList = this.engineeringList.filter((item) => this.ids.includes(item.engineeringId))
      this.$router.push({
        path: '/carbon/business-project/compareData',
        query: {
          projectIdList: `${compareList[0].projectId},${compareList[1].projectId}`,
          engineeringIdList: `${compareList[0].engineeringId},${compareList[1].engineeringId}`,
          mileageList: `${compareList[0].mileage},${compareList[1].mileage}`,
          projectNames: `${compareList[0].engineeringName},${compareList[1].engineeringName}`,
        }
      })
    },
    updatePersonnelData(formData) {
      this.personnelData = { ...formData }
    },
    updateCarData(formData) {
      this.carData = { ...formData }
    }
  }
}
</script>
